package com.yanglanting.disk.spring.control;

import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

public class BaseController {
    private Logger logger = LogManager.getLogger(this.getClass());
    @Resource
    private MessageSource messageSource;

    public String successJson(String key,Object ... args){
        Map<String,Object> rspMap = new HashMap<>();
        rspMap.put("success",true);
        String msg = "";
        try{
            msg = messageSource.getMessage(key,args, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            logger.error("BaseController",e);
            msg = "?" +  key + "?";
        }
        rspMap.put("msg",msg);
        rspMap.put("description",msg);

        return JSON.toJSONString(rspMap);
    }

    public String failJson(String key,Object ... args){
        Map<String,Object> rspMap = new HashMap<>();
        rspMap.put("success",false);
        String msg = "";
        try{
            msg = messageSource.getMessage(key,args, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            logger.error("BaseController",e);
            msg = "?" +  key + "?";
        }
        rspMap.put("msg",msg);
        rspMap.put("description",msg);

        return JSON.toJSONString(rspMap);
    }


    public  String successJson(String key, String code, Object ... args){
        Map<String,Object> rspMap = new HashMap<>();
        rspMap.put("success",true);
        String msg = "";
        try{
            msg = messageSource.getMessage(key,args, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            logger.error("BaseController",e);
            msg = "?" +  key + "?";
        }
        rspMap.put("msg",msg);
        rspMap.put("description",msg);
        rspMap.put("code",code);

        return JSON.toJSONString(rspMap);
    }
}
